package com.mazong.servershirodemo.controller;

import com.mazong.servershirodemo.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Controller
public class LoginController {

    // http://localhost:8000/login?userName=wsl&userPass=123456
    @RequestMapping("/login")
    public String login(TbUser user, Model model) {

        if(user.getUserName() == null) {
            log.info("login, userName is null");
            return "/login";
        }

        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUserName(),
                user.getUserPass()
        );
        log.info("login, userName={},userPass={}", user.getUserName(), user.getUserPass());

        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (AuthenticationException e) {
            //e.printStackTrace();
            log.info("login,账号或密码错误");
            model.addAttribute("msg", "账号或密码错误！");
            return "/login";
        } catch (AuthorizationException e) {
            //e.printStackTrace();
            log.info("login,没有权限");
            model.addAttribute("msg", "没有权限！");
            return "/login";
        }

        return "/index";
    }


    @RequestMapping("/product/select")
    public String select() {
        return "/product/select";
    }

    @RequestMapping("/product/insert")
    public String insert() {
        return "/product/insert";
    }

    @RequestMapping("/product/delete")
    public String delete() {
        return "/product/delete";
    }

    @RequestMapping("/product/update")
    public String update() {
        return "/product/update";
    }
}
